from PyQt4.QtGui import QWidget,QTreeView,QStandardItemModel,QStandardItem,QBrush,QColor,QFont,QSortFilterProxyModel,QItemSelection,QItemSelectionModel
from PyQt4 import QtCore
from PyQt4.QtCore import QString,Qt,QVariant,QStringList
import xml.etree.ElementTree as ET
import sys,importlib,os
from KCharts.ui_KIndicatorTreeWidget import Ui_KIndicatorTreeWidget
import cPickle as pickle
class KIndicatorTreeView(QTreeView):
	''' The UI of strategy batch test '''
	IndicatorChanged=QtCore.pyqtSignal(dict) # tell other indicator selection is updated
	def __init__(self, parent=None):
		super(KIndicatorTreeView, self).__init__(parent)

		
		# setup model
		tmodel=KIndicatorTreeModel(self)
		self.setModel(tmodel)
		tmodel.UpdateIndicatorList()
		tmodel.itemChanged.connect(self.OnItemChanged)
		
		# setup view
		self.setColumnWidth(0,150)
		self.setIndentation(10)
		self.expandAll()
		self.setSortingEnabled(True)
		self.setSelectionBehavior(self.SelectRows)
		self.setSelectionMode(self.SingleSelection)
		self.setEditTriggers(self.NoEditTriggers)
		
		mselectmodel=QItemSelectionModel(tmodel)
		#select first strategy by default
		parentitem=self.model().item(0,0)		
		mselectmodel.select(parentitem.child(0,0).index(),QItemSelectionModel.Select)
		self.setSelectionModel(mselectmodel)
	
	def OnItemChanged(self,itemobj):
		# triggered when 
		classname=itemobj.data(KIndicatorTreeModel.ClassRole).toString() # find class name 
		viewclassname=itemobj.data(KIndicatorTreeModel.ViewClassRole).toString()
		windowname=itemobj.data(KIndicatorTreeModel.WindowRole).toString()
		iselected=(itemobj.checkState()==Qt.Checked)
		paradict={}
		paradict['class']=classname
		paradict['viewclass']=viewclassname
		paradict['windowname']=windowname
		paradict['checkstatus']=iselected
		self.IndicatorChanged.emit(paradict)
	
		
	def ReSendAllCheckedItem(self):
		# call this function whenever new chart is added to charswidgets so the new chart can know existing selection
		
		itemlist=self.model().GetAllCheckedItems()
		for each_item in itemlist:
			self.OnItemChanged(each_item)



	

class KIndicatorTreeModel(QStandardItemModel):
	
	ClassRole=Qt.UserRole
	ViewClassRole=Qt.UserRole+1	
	WindowRole=Qt.UserRole+2

	def __init__(self, parent=None):
		super(KIndicatorTreeModel, self).__init__(parent)
		self.txtfont=QFont("Times", 11)
		# load config
		self.configpath='KIndicatorSetting.txt'
		self.checkedlist=self.Load()


	def data(self,index,role):
		# overide
		if role==Qt.FontRole:
			return self.txtfont
		else:
			return QStandardItemModel.data(self,index,role)

	def OnSetupColumns(self):
		#called when setting up columns
		HeaderLabels=['Name','Summary']
		self.setColumnCount(2)
		for each_index in range(0,len(HeaderLabels)):
			self.setHeaderData(each_index, Qt.Horizontal,QString(HeaderLabels[each_index]))	
		ColNames=['name','summary']
		return ColNames
	
	def OnClear(self):
		pass
	
	def OnSave(self):
		# save checked items to file

		items=self.GetAllCheckedItems()
		itemnamelist=[]
		for each_item in items:
			itemstr=str(each_item.data(Qt.DisplayRole).toString())	
			itemnamelist.append(itemstr)
			
		fileobj=open(self.configpath,'wb')
	
		pickle.dump(itemnamelist,fileobj)
		fileobj.close()
		
	def Load(self):
		if os.stat(self.configpath)[6]==0: ## skip empty file
			return [];		
		fileobj=open(self.configpath,'r')
		checkedlist=pickle.load(fileobj)
		fileobj.close()
		return checkedlist;
	
	def GetAllCheckedItems(self):
		itemlist=[]
		for rowindex in range(0,self.rowCount()):
			for colindex in range(0,self.columnCount()):
				mitem=self.item(rowindex,colindex)
				if mitem :
					if mitem.isCheckable() and mitem.checkState()==Qt.Checked:
						itemlist.append(mitem)
					self.__GetAllCheckedSubItem(mitem,itemlist)
		return itemlist
					
					
	def __GetAllCheckedSubItem(self,pitem,itemlist):
		for rowindex in range(0,pitem.rowCount()):
			for colindex in range(0,pitem.columnCount()):
				mitem=pitem.child(rowindex,colindex)
				if mitem :
					if mitem.isCheckable() and mitem.checkState()==Qt.Checked:						
						itemlist.append(mitem)

		
		
	
	def UpdateIndicatorList(self):
	# build the model with specified fields		
		self.clear()
		ColNames=self.OnSetupColumns()
		pathname=r'D:\Dropbox\Trading2013\KunTrading\ConfigFiles\KIndicatorList.xml'
		tree = ET.parse(pathname)
		root = list(tree.getroot())
		rowindex=0
	
		for child in root:  # for each strategy folder
			mitem=QStandardItem()
			mitem.setData(child.get('name'),Qt.DisplayRole)
			self.setItem(rowindex, 0, mitem);	
			subrowindex=0
			for each_strat in child: # for each strategy
				colindex=0
				for each_col in ColNames:
					subitem=QStandardItem()
					mitem.setChild(subrowindex,colindex,subitem)
					itemname=each_strat.find(each_col).text.strip("\"")
					subitem.setData(itemname,Qt.DisplayRole)
					subitem.setData(each_strat.find('class').text.strip("\""),KIndicatorTreeModel.ClassRole)
					subitem.setData(each_strat.find('viewclass').text.strip("\""),KIndicatorTreeModel.ViewClassRole)
					subitem.setData(each_strat.find('windowname').text.strip("\""),KIndicatorTreeModel.WindowRole)
					if colindex==0:
						subitem.setCheckable(True) # make the first column checkable
						if itemname in self.checkedlist:
							subitem.setCheckState(Qt.Checked)
					colindex+=1
				subrowindex+=1
			rowindex+=1	






